package com.party.mobile.web.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.party.authorization.annotation.Authorization;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.utils.PartyCode;
import com.party.common.utils.PasswordUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.*;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.version.VersionManager;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IThirdPartyUserService;
import com.party.core.service.partner.IMemberPartnerPrivilegeService;
import com.party.core.service.system.ISysRoleService;
import com.party.core.service.version.IVersionManagerService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.CopartnerMemberBizService;
import com.party.mobile.biz.member.LoginBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.input.*;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.LoginInfoOutput;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.utils.ValidatedUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 会员登陆控制层
 * party
 * Created by wei.li
 * on 2016/9/22 0022.
 */

@Controller
@RequestMapping(value = "member/login")
public class LoginController {

    protected static Logger logger = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    IMemberService memberService;

    @Autowired
    MemberBizService memberBizService;

    @Autowired
    private CopartnerMemberBizService copartnerMemberBizService;

    @Autowired
    RedisTokenManager redisTokenManager;

    @Autowired
    IVersionManagerService versionManagerService;

    @Autowired
    IThirdPartyUserService thirdPartyUserService;

    @Autowired
    CurrentUserBizService currentUserBizService;

    @Autowired
    private IMemberPartnerPrivilegeService memberPartnerPrivilegeService;

    @Autowired
    private LoginBizService loginBizService;

    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 获取第三方登录开关信息
     *
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/getLoginInfo")
    public AjaxResult getLoginInfo(LoginInfoInput infoInput, BindingResult result) {
        VersionManager versionManager = new VersionManager();
        versionManager = LoginInfoInput.transform(versionManager, infoInput);
        versionManager.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<VersionManager> list = versionManagerService.list(versionManager);
        LoginInfoOutput info = new LoginInfoOutput();
        if (list.size() > 0) {
            versionManager = list.get(0);
            info = LoginInfoOutput.transform(versionManager);
        } else {
            //如果没有，默认给开放第三方登录
            info.setLoginQQ(YesNoStatus.YES.getCode());
            info.setLoginWX(YesNoStatus.YES.getCode());
        }
        return AjaxResult.success(info);
    }

    /**
     * 获取app版本信息
     */
    @ResponseBody
    @RequestMapping(value = "/getNewVersion")
    public AjaxResult getVersion(String type) {
        VersionManager versionManager = new VersionManager();
        if (Strings.isNullOrEmpty(type)) {
            type = "app";
        }
        versionManager.setType(type);
        List<VersionManager> list = versionManagerService.list(versionManager);
        VersionManager version = null;
        if (list != null && list.size() > 0) {
            version = list.get(0);
        }
        return AjaxResult.success(version);
    }

    /**
     * 会员登录
     *
     * @param loginInput 登陆输入视图
     * @param result     验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/login")
    public AjaxResult login(@Validated LoginInput loginInput, BindingResult result) {

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        //查找用户
        Member member = memberService.findByLoginName(loginInput.getUsername(), Member.MEMBER_PERSONAL);
        if (null == member) {
            return AjaxResult.error(PartyCode.MEMBER_UNEXIST, "用户不存在");
        }
        boolean hasPartner = sysRoleService.hasRole(member.getId(), RoleEnum.PARTNER_ROLE.getCode());
        boolean hasCosponsor = sysRoleService.hasRole(member.getId(), RoleEnum.COSPONSOR_ROLE.getCode());
        if (hasPartner || hasCosponsor) {
            return AjaxResult.error(PartyCode.MEMBER_UNEXIST, "用户不存在");
        }

        boolean validate = PasswordUtils.validatePassword(loginInput.getPassword(), member.getPassword());
        //验证凭证
        if (!validate) {
            return AjaxResult.error(PartyCode.PASSWORD_UNMATCH, "用户名密码不匹配");
        }

        AjaxResult ajaxResult = AjaxResult.success();
        MemberOutput memberOutput = memberBizService.getLoginMember(member);
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }

    /**
     * 合伙人APP登录
     *
     * @param loginInput 登陆输入视图
     * @param result     验证结果
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/copartnerLogin")
    public AjaxResult copartnerLogin(@Validated LoginInput loginInput, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        try {
            MemberOutput memberOutput = copartnerMemberBizService.copartnerPasswordLogin(loginInput);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟登陆异常", e);
            return AjaxResult.error(100, "登陆异常");
        }
    }

    /**
     * 合伙人APP登录V2
     *
     * @param loginInput 登陆输入视图
     * @param result     验证结果
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/copartnerLogin/v2", method = RequestMethod.POST)
    public AjaxResult copartnerLoginV2(@Validated LoginInput loginInput, BindingResult result, String identityName) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        if (StringUtils.isEmpty(identityName)) {
            throw new BusinessException(PartyCode.MEMBER_UNEXIST, "身份不能为空");
        }

        try {
            MemberOutput memberOutput = copartnerMemberBizService.copartnerPwdLoginV2(loginInput, identityName);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟登陆异常", e);
            return AjaxResult.error(100, "登陆异常");
        }
    }

    /**
     * ceo户外联盟手机验证码登陆
     *
     * @param input  输入参数
     * @param result 验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "copartnerVerifyCodeLogin/v2", method = RequestMethod.POST)
    public AjaxResult copartnerVerifyCodeLoginV2(@Validated VerifyCodeLoginInput input, BindingResult result, String identityName) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        try {
            if (StringUtils.isEmpty(input.getCountryCode())) {
                input.setCountryCode(Constant.CHINA_MOBILE_CODE);
            }
            MemberOutput memberOutput = copartnerMemberBizService.copartnerVerifyLoginV2(input, identityName);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟验证码登录注册异常", e);
            return AjaxResult.error(100, "登录异常");
        }
    }

    /**
     * ceo户外联盟手机验证码登陆
     *
     * @param input  输入参数
     * @param result 验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = {"verifyCodeLogin", "copartnerVerifyCodeLogin"})
    public AjaxResult copartnerVerifyCodeLogin(@Validated VerifyCodeLoginInput input, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        try {
            if (StringUtils.isEmpty(input.getCountryCode())) {
                input.setCountryCode(Constant.CHINA_MOBILE_CODE);
            }
            MemberOutput memberOutput = copartnerMemberBizService.copartnerVerifyLogin(input);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟验证码登录注册异常", e);
            return AjaxResult.error(100, "登录异常");
        }
    }

    /**
     * 机构APP登录
     *
     * @param loginInput 登陆输入视图
     * @param result     验证结果
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/partnerLogin")
    public AjaxResult partnerLogin(@Validated LoginInput loginInput, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        try {
            //查找用户
            MemberGroup member = memberGroupService.findByLoginName(loginInput.getUsername(), Constant.MEMBER_ORGANIZATION);
            if (null == member) {
                return AjaxResult.error(PartyCode.MEMBER_UNEXIST, "用户不存在");
            }

            boolean validate = PasswordUtils.validatePassword(loginInput.getPassword(), member.getPassword());
            //验证凭证
            if (!validate) {
                return AjaxResult.error(PartyCode.PASSWORD_UNMATCH, "用户名密码不匹配");
            }

            boolean isXzgsAdmin = sysRoleService.hasRole(member.getId(), RoleEnum.XZGS_ADMIN.getCode());
            boolean isBranchManager = sysRoleService.hasRole(member.getId(), RoleEnum.BRANCH_MANAGER.getCode());
            if (isXzgsAdmin || isBranchManager) {
                String logo = member.getLogo();
                String realName = member.getRealname();
                String username = member.getUsername();
                member= memberGroupService.get(member.getPartnerId());
                member.setLogo(logo);
                member.setRealname(realName);
                member.setUsername(username);
            }

            // 是否有合作商角色
            boolean isPartner = sysRoleService.hasRole(member.getId(), RoleEnum.PARTNER_ROLE.getCode());
            // 是否有行知公社角色
            boolean isXzgs = sysRoleService.hasRole(member.getId(), RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
            // 是否有admin角色
            boolean isAdmin = sysRoleService.hasRole(member.getId(), "admin");
            // 是否为平台管理角色
            boolean isPlant = sysRoleService.hasRoleType(member.getId(), RoleType.PLATFORM_ROLE);

            boolean isTwoLevelChildren = false;
            boolean isSubManager = false;
            if (StringUtils.isNotEmpty(member.getPartnerId())) {
                //分社队长
                isTwoLevelChildren = sysRoleService.hasRole(member.getId(), RoleEnum.BRANCH_TEAM_LEADER.getCode());
                //创始理事长
                isSubManager = sysRoleService.hasRole(member.getId(), RoleEnum.BRANCH_DIRECTOR.getCode());
            }

            boolean hasAdminPrivilege = false;
            if (isAdmin || isPlant) {
                hasAdminPrivilege = true;
            }

            if (!isPartner && !hasAdminPrivilege) {
                return AjaxResult.error(PartyCode.ROLE_NOT_MATCH, "该账号没有权限");
            }
            MemberOutput memberOutput = memberBizService.getLoginMember(member);
            Map<String, Object> o = (Map<String, Object>) JSONObject.toJSON(memberOutput);
            o.put("isAdmin", hasAdminPrivilege);
            o.put("isXzgs", isXzgs ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            o.put("isTwoLevelChildren",isTwoLevelChildren ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            o.put("isSubManager",isSubManager ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            o.put("isXzgsAdmin",isXzgsAdmin ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            o.put("isChild",member.getPartnerId()!=null ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            if (isPartner) {
                if (StringUtils.isEmpty(member.getPartnerId())) {
                    o.put("isChildAccount", false);
                } else {
                    o.put("isChildAccount", true);
                }
            }
            // todo 这个不知道是干吗的？
            List<Map<String, String>> partners = memberPartnerPrivilegeService.findByMemberId(member.getId());
            o.put("isShowAll", partners.size() > 0 ? false : true);
            return AjaxResult.success(o);
        } catch (Exception e) {
            logger.error("机构登录异常", e);
            return AjaxResult.error(100, "登录失败");
        }
    }

    /**
     * 获取登陆用户信息
     *
     * @param request 请求参数
     * @return 加护数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "getLoginMember")
    public AjaxResult getLoginMember(HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        MemberOutput memberOutput;
        try {
            memberOutput = memberBizService.getLoginMember(currentUser);
        } catch (Exception e) {
            logger.error("getLoginMember异常", e);
            ajaxResult.setDescription("服务器异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }


    /**
     * 登陆接口2.0
     *
     * @param loginInput 输入参数
     * @param result     验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "login2")
    public AjaxResult login2(@Validated LoginInput loginInput, BindingResult result) {

        AjaxResult ajaxResult = new AjaxResult();
        //数据验证
        if (result.hasErrors()) {
            return ValidatedUtils.validated(ajaxResult, result);
        }

        //登陆验证
        Member member = memberService.findByLoginName(loginInput.getUsername(), Member.MEMBER_PERSONAL);

        if (null == member) {
            ajaxResult.setErrorCode(PartyCode.MEMBER_UNEXIST);
            ajaxResult.setDescription("用户不存在");
            return ajaxResult;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(member.getId(), loginInput.getPassword());
        token.setRememberMe(true);

        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();

        try {
            currentUser.login(token);
        } catch (IncorrectCredentialsException ex) {
            logger.debug("用户登陆验证不通过", ex);
            ajaxResult.setErrorCode(PartyCode.PASSWORD_UNMATCH);
            ajaxResult.setDescription("用户名密码不匹配");
            return ajaxResult;
        }

        MemberOutput memberOutput = memberBizService.getLoginMember(member);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }


    /**
     * 登出接口2.0
     *
     * @return 登出
     */
    @ResponseBody
    @RequestMapping(value = "logout2")
    public AjaxResult logout2() {
        AjaxResult ajaxResult = new AjaxResult();
        SecurityUtils.getSubject().logout();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 登出
     *
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/logout")
    public AjaxResult logout(HttpServletRequest request) {
        //删除token
        //String key = stringJedis.getValue(WechatPayCode.REQUEST_CURRENT_KEY);
        String token = request.getHeader(com.party.authorization.utils.Constant.HTTP_HEADER_NAME);
        if (StringUtils.isNotEmpty(token)) {
            redisTokenManager.delRelationshipByToken(token);
        }
        return AjaxResult.success();
    }

    /**
     * 使用微信登录
     *
     * @param thirdPartyUserInput 第三方登陆输入视图
     * @param result              验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/tp_login")
    public AjaxResult tp_login(@Validated ThirdPartyUserInput thirdPartyUserInput, BindingResult result, HttpServletRequest request) {

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        AjaxResult ajaxResult = AjaxResult.success();
        try {
            MemberOutput memberOutput = memberBizService.thirdPartyUserLogin(thirdPartyUserInput, request);
            ajaxResult.setData(memberOutput);
        } catch (Exception e) {
            logger.error("tp_login登录异常：{}", e);
            e.printStackTrace();
            ajaxResult.setSuccess(false);
        }

        return ajaxResult;
    }


    /**
     * 第三方账户登录2.0
     *
     * @param thirdPartyUserInput 输入参数
     * @param result              验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "tp_login2")
    public AjaxResult tp_login2(@Validated ThirdPartyUserInput thirdPartyUserInput, BindingResult result, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        //数据验证
        if (result.hasErrors()) {
            return ValidatedUtils.validated(ajaxResult, result);
        }
        MemberOutput memberOutput = memberBizService.thirdPartyUserLogin(thirdPartyUserInput, request);

        //查找用户
        ThirdPartyUser thirdPartyUser = thirdPartyUserService.getByOpenId(thirdPartyUserInput.getOpenId());
        UsernamePasswordToken token = new UsernamePasswordToken(thirdPartyUser.getMemberId(), Constant.DEFALT_PASSWORD);
        token.setRememberMe(true);

        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();

        try {
            currentUser.login(token);
        } catch (IncorrectCredentialsException ex) {
            logger.debug("第三方用户登陆验证不通过", ex);
            ajaxResult.setErrorCode(PartyCode.PASSWORD_UNMATCH);
            ajaxResult.setDescription("用户名密码不匹配");
            return ajaxResult;
        }
        ajaxResult.setData(memberOutput);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 手机用户绑定第三方授权
     *
     * @param thirdPartyUserInput 第三方登陆输入视图
     * @param result              验证结果
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/bindThird")
    public AjaxResult bindThird(@Validated ThirdPartyUserInput thirdPartyUserInput, HttpServletRequest request, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        AjaxResult ajaxResult = AjaxResult.success();
        MemberOutput memberOutput = memberBizService.bindThird(thirdPartyUserInput, request);
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }

    /**
     * 第三方授权账号绑定手机号
     *
     * @param bindInput 手机号及验证码视图
     * @param result    验证结果
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/bindPhone")
    public AjaxResult bindPhone(@Validated BindInput bindInput, HttpServletRequest request, BindingResult result) {

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        //验证验证码
        /*String verifyCode = stringJedis.getValue(bindInput.getPhone());
        if (null == verifyCode || !bindInput.getVerifyCode().equals(verifyCode)) {
            return AjaxResult.error(PartyCode.VERIFY_CODE_ERROR, "手机验证码不一致");
        }*/

        MemberOutput memberOutput;
        try {
            //CurrentUser currentUser = memberBizService.bindPhoneBiz(bindInput.getPhone(), bindInput.getVerifyCode(), request);
            CurrentUser currentUser = memberBizService.bindPhoneBiz2(bindInput.getPhone(), bindInput.getVerifyCode(),
                    bindInput.getCountryCode(), request);

            Member dbMember = memberService.get(currentUser.getId());
            dbMember.setCountryCode(bindInput.getCountryCode());
            memberService.update(dbMember);

            memberOutput = memberBizService.getLoginMember(dbMember);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error("绑定手机异常", be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("绑定手机异常", e);
            return AjaxResult.error(100, "绑定手机异常");
        }
    }

    /**
     * @param lgToken 登录token
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 更改状态为已扫描
     * @Date 10:25 2019/1/30
     **/
    @ResponseBody
    @RequestMapping(value = "scanQrCode", method = RequestMethod.POST)
    public AjaxResult scanQrCode(String lgToken) {
        try {
            if (StringUtils.isEmpty(lgToken)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "token不能为空");
            }

            ScanLoginOutput loginOutput = loginBizService.getLoginOutputRedis(lgToken);
            if (null != loginOutput) {
                if (ScanLoginStatus.SCAN_SUCCESS.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.SCAN_SUCCESS_CONFIRM.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.SCAN_SUCCESS_LOGIN.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.QR_INVALID.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.SCAN_SUCCESS_CANCEL.getCode().equals(loginOutput.getCode())) {
                    return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
                }

                loginOutput.setCode(ScanLoginStatus.SCAN_SUCCESS.getCode());
                loginBizService.setLoginOutRedis(loginOutput);
            } else {
                return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("扫描二维码异常", e);
            return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
        }
    }

    /**
     * @param lgToken 登录token
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 扫码二维码 确认登录
     * @Date 10:25 2019/1/30
     **/
    @Authorization
    @ResponseBody
    @RequestMapping(value = "scanQrCodeConfirm", method = RequestMethod.POST)
    public AjaxResult scanQrCodeConfirm(String lgToken, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(lgToken)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "token不能为空");
            }

            ScanLoginOutput loginOutput = loginBizService.getLoginOutputRedis(lgToken);
            if (null != loginOutput) {
                if (ScanLoginStatus.SCAN_SUCCESS_CONFIRM.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.SCAN_SUCCESS_LOGIN.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.QR_INVALID.getCode().equals(loginOutput.getCode())
                        || ScanLoginStatus.SCAN_SUCCESS_CANCEL.getCode().equals(loginOutput.getCode())) {
                    return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
                }

                CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
                MemberGroup member = memberGroupService.get(currentUser.getId());
                loginOutput.setLoginName(member.getUsername());
                loginOutput.setMemberId(member.getId());
                loginOutput.setCode(ScanLoginStatus.SCAN_SUCCESS_CONFIRM.getCode());
                loginBizService.setLoginOutRedis(loginOutput);
                return AjaxResult.success();
            } else {
                return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
            }
        } catch (Exception e) {
            logger.error("扫描二维码 确认登录 异常", e);
            loginBizService.doError(lgToken);
            return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
        }
    }

    /**
     * @param lgToken
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 扫码二维码 确认登录
     * @Date 10:25 2019/1/30
     **/
    @ResponseBody
    @RequestMapping(value = "scanQrCodeCancel", method = RequestMethod.POST)
    public AjaxResult scanQrCodeCancel(String lgToken) {
        try {
            if (StringUtils.isEmpty(lgToken)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "token不能为空");
            }

            ScanLoginOutput loginOutput = loginBizService.getLoginOutputRedis(lgToken);
            if (null != loginOutput) {
                loginOutput.setCode(ScanLoginStatus.SCAN_SUCCESS_CANCEL.getCode());
                loginBizService.setLoginOutRedis(loginOutput);
            } else {
                return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("扫描二维码 取消登录 异常", e);
            return AjaxResult.error(ScanLoginStatus.QR_INVALID.getCode(), "二维码已失效");
        }
    }

    // 1、输入手机号码后，根据手机号获取对应的身份列表。
    // 2、验证码登录、账号密码登录，选择身份再登录。

    @ResponseBody
    @RequestMapping(value = "getIdentityByLoginName")
    public AjaxResult getIdentityByLoginName(String loginName) {
        if (StringUtils.isEmpty(loginName)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "手机号不能为空");
        }

        try {
            long start = System.currentTimeMillis();
            List<Map<String, Object>> identities = copartnerMemberBizService.getIdentityByMobile(loginName);
            long end = System.currentTimeMillis();
            logger.info("loginName：{}，用时：{}（ms)", loginName, (end - start));
            return AjaxResult.success(identities);
        } catch (Exception e) {
            logger.error("获取身份异常", e);
            return AjaxResult.error(100, "获取身份异常");
        }
    }

    /**
     * 用户注销
     *
     * @param request
     * @return com.party.mobile.web.dto.AjaxResult
     * @author shenliuhai
     * @date 2020/1/10 15:30
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "cancel/account")
    public AjaxResult cancelAccount(HttpServletRequest request) {

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (null != currentUser) {
            if (null != currentUser.getIsMemberGroup()) {
                if (YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                    return AjaxResult.error(100, "机构账号注销,请联系同行者社群服务平台，联系电话为: 4008-771-663");
                } else if (YesNoStatus.NO.getCode().equals(currentUser.getIsMemberGroup())) {
                    String userId = currentUser.getId();
                    Member member = memberService.get(userId);
                    member.setDelFlag(String.valueOf(1));
                    memberService.update(member);
                    String token = request.getHeader(com.party.authorization.utils.Constant.HTTP_HEADER_NAME);
                    redisTokenManager.delRelationshipByToken(token);
                }
            }
        }
        return AjaxResult.success();
    }


    /**
     * ceo户外联盟用户注销
     *
     * @param userId 用户id
     * @param userId 用户类型
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "userLogout")
    public AjaxResult userLogout(String userId, Integer type,HttpServletRequest request) {
        if (StringUtils.isEmpty(userId) || type == null) {
            return AjaxResult.error(100, "参数为空");
        }
        try {
            if (Constant.MEMBER_PERSONAL == type) {
                Member member = memberService.get(userId);
                if (member == null) {
                    return AjaxResult.error(100, "用户不存在");
                }
                member.setDelFlag(Member.DEL_FLAG_DELETE);
                memberService.update(member);
            }
            if (Constant.MEMBER_ORGANIZATION == type) {
                MemberGroup memberGroup = memberGroupService.get(userId);
                if (memberGroup == null) {
                    return AjaxResult.error(100, "用户不存在");
                }
                memberGroup.setDelFlag(MemberGroup.DEL_FLAG_DELETE);
                memberGroupService.update(memberGroup);
            }

            String oldToken = request.getHeader(com.party.authorization.utils.Constant.HTTP_HEADER_NAME);
            redisTokenManager.delRelationshipByToken(oldToken);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟用户注销异常", e);
            return AjaxResult.error(100, "ceo户外联盟用户注销异常");
        }
        return AjaxResult.success("注销成功");
    }
}
